package com.doraro.platform.config.shiro;

import com.doraro.platform.common.utils.JsonUtil;
import com.doraro.platform.common.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Setter;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Setter
public class RestPermFilter extends PermissionsAuthorizationFilter {
    private JsonUtil util;

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        final String method = ((HttpServletRequest) request).getMethod();
        return method.equals(RequestMethod.OPTIONS.name()) || super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        util.writeJson(httpResponse, new Result().error(HttpStatus.FORBIDDEN, "无权查看"));
        return false;
    }
}
